﻿using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Text.RegularExpressions;

namespace D.Util.UtilFileIO
{
    /// <summary>
    /// 文件处理
    /// System.Drawing.Common
    /// </summary>
    public static class FileUtil
    {
        #region 检测指定目录是否存在

        /// <summary> 
        /// 检测指定目录是否存在 
        /// </summary> 
        /// <param name="directoryPath">目录的绝对路径</param>         
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }

        #endregion

        #region 检测指定文件是否存在 

        /// <summary> 
        /// 检测指定文件是否存在 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param>         
        public static bool IsExistFile(string filePath)
        {
            return File.Exists(filePath);
        }

        #endregion

        #region 检测指定目录是否为空 

        /// <summary> 
        /// 检测指定目录是否为空 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param>         
        public static bool IsEmptyDirectory(string directoryPath)
        {
            try
            {
                //判断是否存在文件 
                string[] fileNames = GetFileNames(directoryPath);
                if (fileNames.Length > 0)
                {
                    return false;
                }

                //判断是否存在文件夹 
                string[] directoryNames = GetDirectories(directoryPath);
                if (directoryNames.Length > 0)
                {
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return true;
            }
        }

        #endregion

        #region 检测目录中是否存在指定文件

        /// <summary> 
        /// 检测目录中是否存在指定文件
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param> 
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。范例："Log*.xml"表示搜索所有以Log开头的Xml文件</param> 
        public static bool Contains(string directoryPath, string searchPattern)
        {
            try
            {
                //获取指定的文件列表 
                string[] fileNames = GetFileNames(directoryPath, searchPattern, false);

                //判断指定文件是否存在 
                if (fileNames.Length == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        /// <summary> 
        /// 检测指定目录中是否存在指定的文件 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param> 
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。 
        /// 范例："Log*.xml"表示搜索所有以Log开头的Xml文件。</param>  
        /// <param name="isSearchChild">是否搜索子目录</param> 
        public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild)
        {
            try
            {
                //获取指定的文件列表 
                string[] fileNames = GetFileNames(directoryPath, searchPattern, true);

                //判断指定文件是否存在 
                if (fileNames.Length == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        #endregion

        #region 创建目录

        /// <summary> 
        /// 创建目录 
        /// </summary> 
        /// <param name="directoryPath">目录的绝对路径</param> 
        public static void CreateDirectory(string directoryPath)
        {
            //如果目录不存在则创建该目录 
            if (!IsExistDirectory(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
        }

        /// <summary>
        ///     创建指定目录
        /// </summary>
        /// <param name="targetDir"></param>
        //public static void CreateDirectory(string targetDir)
        //{
        //    var directoryInfo = new DirectoryInfo(targetDir);

        //    if (!directoryInfo.Exists) directoryInfo.Create();
        //}
         
        #endregion

        #region 创建文件 

        /// <summary> 
        /// 创建文件
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        public static void CreateFile(string filePath)
        {
            try
            {
                //如果文件不存在则创建该文件 
                if (!IsExistFile(filePath))
                {
                    //创建一个FileInfo对象 
                    FileInfo file = new FileInfo(filePath);

                    //创建文件 
                    FileStream fs = file.Create();

                    //关闭文件流 
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary> 
        /// 创建并写入文件
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        /// <param name="buffer">二进制流数据</param> 
        public static void CreateFile(string filePath, byte[] buffer)
        {
            try
            {
                //如果文件不存在则创建该文件 
                if (!IsExistFile(filePath))
                {
                    //创建一个FileInfo对象 
                    FileInfo file = new FileInfo(filePath);

                    //创建文件 
                    FileStream fs = file.Create();

                    //写入二进制流 
                    fs.Write(buffer, 0, buffer.Length);

                    //关闭文件流 
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        #endregion

        #region 获取文件行数

        /// <summary> 
        /// 获取文件行数 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param>         
        public static int GetLineCount(string filePath)
        {
            //将文本文件的各行读到一个字符串数组中 
            string[] rows = File.ReadAllLines(filePath);

            //返回行数 
            return rows.Length;
        }

        #endregion

        #region 获取文件大小

        /// <summary> 
        /// 获取文件大小
        /// 单位为Byte 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param>         
        public static int GetFileSize(string filePath)
        {
            //创建一个文件对象 
            FileInfo fi = new FileInfo(filePath);

            //获取文件的大小 
            return (int)fi.Length;
        }

        /// <summary> 
        /// 获取文件大小
        /// 单位为KB 
        /// </summary> 
        /// <param name="filePath">文件的路径</param>         
        public static double GetFileSizeByKB(string filePath)
        {
            //创建一个文件对象 
            FileInfo fi = new FileInfo(filePath);

            //获取文件的大小 
            return Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024);
        }

        /// <summary> 
        /// 获取文件大小
        /// 单位为MB 
        /// </summary> 
        /// <param name="filePath">文件的路径</param>         
        public static double GetFileSizeByMB(string filePath)
        {
            //创建一个文件对象 
            FileInfo fi = new FileInfo(filePath);

            //获取文件的大小 
            return Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024);
        }

        /// <summary> 
        /// 获取指定目录文件大小
        /// 单位为KB 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param>         
        public static double GetDirectoryFileSizeByKB(string directoryPath)
        {
            var files = GetFileNames(directoryPath);
            Double fileSize = 0;

            foreach (var file in files)
            {
                //创建一个文件对象 
                FileInfo fi = new FileInfo(file);
                //获取文件的大小 
                fileSize += Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024);
            }

            return fileSize;
        }

        /// <summary> 
        /// 获取指定目录文件大小
        /// 单位为MB 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param>         
        public static double GetDirectoryFileSizeByMB(string directoryPath)
        {
            var files = GetFileNames(directoryPath);
            Double fileSize = 0;

            foreach (var file in files)
            {
                //创建一个文件对象 
                FileInfo fi = new FileInfo(file);
                //获取文件的大小 
                fileSize += Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024);
            }

            return fileSize;
        }

        /// <summary> 
        /// 获取指定目录文件大小
        /// 单位为MB 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param> 
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。 
        /// 范例："Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
        /// <param name="isSearchChild">指定目录的绝对路径</param>
        public static double GetDirectoryFileSizeByMB(string directoryPath, string searchPattern, bool isSearchChild)
        {
            var files = GetFileNames(directoryPath, searchPattern, isSearchChild);
            Double fileSize = 0;

            foreach (var file in files)
            {
                //创建一个文件对象 
                FileInfo fi = new FileInfo(file);
                //获取文件的大小 
                fileSize += Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024);
            }

            return fileSize;
        }

        /// <summary> 
        /// 获取指定目录文件大小
        /// 单位为GB 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param>         
        public static double GetDirectoryFileSizeByGB(string directoryPath)
        {
            var files = GetFileNames(directoryPath);
            Double fileSize = 0;

            foreach (var file in files)
            {
                //创建一个文件对象 
                FileInfo fi = new FileInfo(file);
                //获取文件的大小 
                fileSize += Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024 / 1024);
            }

            return fileSize;
        }

        #endregion

        #region 获取指定目录中的文件列表

        /// <summary> 
        /// 获取指定目录中所有文件列表 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param>         
        public static string[] GetFileNames(string directoryPath)
        {
            //如果目录不存在，则抛出异常 
            if (!IsExistDirectory(directoryPath))
            {
                throw new FileNotFoundException();
            }
            //获取文件列表 
            return Directory.GetFiles(directoryPath);
        }

        /// <summary> 
        /// 获取指定目录及子目录中所有文件列表 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param> 
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。 
        /// 范例："Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 
        /// <param name="isSearchChild">是否搜索子目录</param> 
        public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)
        {
            //如果目录不存在，则抛出异常 
            if (!IsExistDirectory(directoryPath))
            {
                throw new FileNotFoundException();
            }
            try
            {
                if (isSearchChild)
                {
                    return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
                }
            }
            catch (IOException ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 获取指定目录中的子目录列表

        /// <summary> 
        /// 获取指定目录中所有子目录列表
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param>         
        public static string[] GetDirectories(string directoryPath)
        {
            try
            {
                return Directory.GetDirectories(directoryPath);
            }
            catch (IOException ex)
            {
                throw ex;
            }
        }

        /// <summary> 
        /// 获取指定目录及子目录中所有子目录列表 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param> 
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。 
        /// 范例："Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 
        /// <param name="isSearchChild">是否搜索子目录</param> 
        public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
        {
            try
            {
                if (isSearchChild)
                {
                    return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
                }
            }
            catch (IOException ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 写入内容

        /// <summary> 
        /// 写入内容 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        /// <param name="content">写入的内容</param>         
        public static void WriteText(string filePath, string content)
        {
            //向文件写入内容 
            File.WriteAllText(filePath, content);
        }

        #endregion

        #region 追加内容

        /// <summary> 
        /// 追加内容 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        /// <param name="content">写入的内容</param> 
        public static void AppendText(string filePath, string content)
        {
            File.AppendAllText(filePath, content);
        }

        #endregion

        #region 复制文件

        /// <summary> 
        /// 复制文件 
        /// </summary> 
        /// <param name="sourceFilePath">源文件的绝对路径</param> 
        /// <param name="destFilePath">目标文件的绝对路径</param> 
        public static void Copy(string sourceFilePath, string destFilePath)
        {
            File.Copy(sourceFilePath, destFilePath, true);
        }

        #endregion

        #region 移动目录 

        /// <summary> 
        /// 移动目录 
        /// </summary> 
        /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param> 
        /// <param name="descDirectoryPath">移动到的目录的绝对路径</param> 
        public static void Move(string sourceFilePath, string descDirectoryPath)
        {
            //获取源文件的名称 
            string sourceFileName = GetFileName(sourceFilePath);

            if (IsExistDirectory(descDirectoryPath))
            {
                //如果目标中存在同名文件,则删除 
                if (IsExistFile(descDirectoryPath + "\\" + sourceFileName))
                {
                    DeleteFile(descDirectoryPath + "\\" + sourceFileName);
                }

                //将文件移动到指定目录 
                File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName);
            }
        }

        #endregion

        #region 将流读取到缓冲区中 

        /// <summary> 
        /// 将流读取到缓冲区中 
        /// </summary> 
        /// <param name="stream">原始流</param> 
        public static byte[] StreamToBytes(Stream stream)
        {
            try
            {
                //创建缓冲区 
                byte[] buffer = new byte[stream.Length];

                //读取流 
                stream.Read(buffer, 0, Convert.ToInt32(stream.Length));

                //返回流 
                return buffer;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                //关闭流 
                stream.Close();
            }
        }

        #endregion

        #region 将文件读取到缓冲区中

        /// <summary> 
        /// 将文件读取到缓冲区中 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        public static byte[] FileToBytes(string filePath)
        {
            //获取文件的大小  
            int fileSize = GetFileSize(filePath);

            //创建一个临时缓冲区 
            byte[] buffer = new byte[fileSize];

            //创建一个文件流 
            FileInfo fi = new FileInfo(filePath);

            FileStream fs = fi.Open(FileMode.Open);

            try
            {
                //将文件流读入缓冲区 
                fs.Read(buffer, 0, fileSize);

                return buffer;
            }
            catch (IOException ex)
            {
                throw ex;
            }
            finally
            {
                //关闭文件流 
                fs.Close();
            }
        }

        #endregion

        #region 将文件读取到字符串中 

        /// <summary> 
        /// 将文件读取到字符串中 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        public static string FileToString(string filePath)
        {
            return FileToString(filePath, Encoding.UTF8);
        }

        /// <summary> 
        /// 将文件读取到字符串中 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        /// <param name="encoding">字符编码</param> 
        public static string FileToString(string filePath, Encoding encoding)
        {
            //创建流读取器 
            StreamReader reader = new StreamReader(filePath, encoding);
            try
            {
                //读取流 
                return reader.ReadToEnd();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                //关闭流读取器 
                reader.Close();
            }
        }

        #endregion

        #region 获取文件名(包含扩展名) 

        /// <summary>
        ///     从路径中获取文件名称（包括后缀）
        /// </summary>
        /// <param name="filePath">路径</param>
        /// <returns>文件名称（包括后缀）</returns>
        public static string GetFileName(string filePath)
        {
            return Path.GetFileName(filePath);
        }

        #endregion

        #region 获取文件名(不包含扩展名) 

        /// <summary> 
        /// 获取文件名
        /// 不包含扩展名
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param>         
        public static string GetFileNameWithNoExtension(string filePath)
        {
            //获取文件的名称 
            FileInfo fi = new FileInfo(filePath);
            return fi.Name.Split('.')[0];
        }

        #endregion

        #region 获取扩展名

        /// <summary> 
        /// 获取扩展名 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param>         
        public static string GetExtension(string filePath)
        {
            //获取文件的名称 
            FileInfo fi = new FileInfo(filePath);
            return fi.Extension;
        }

        #endregion

        #region 清空指定目录 

        /// <summary> 
        /// 清空指定目录下所有文件及子目录,但该目录依然保存. 
        /// </summary> 
        /// <param name="directoryPath">指定目录的绝对路径</param> 
        public static void ClearDirectory(string directoryPath)
        {
            if (IsExistDirectory(directoryPath))
            {
                //删除目录中所有的文件 
                string[] fileNames = GetFileNames(directoryPath);
                for (int i = 0; i < fileNames.Length; i++)
                {
                    DeleteFile(fileNames[i]);
                }

                //删除目录中所有的子目录 
                string[] directoryNames = GetDirectories(directoryPath);
                for (int i = 0; i < directoryNames.Length; i++)
                {
                    DeleteDirectory(directoryNames[i]);
                }
            }
        }

        #endregion

        #region 清空文件内容

        /// <summary> 
        /// 清空文件内容 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        public static void ClearFile(string filePath)
        {
            //删除文件 
            File.Delete(filePath);

            //重新创建该文件 
            CreateFile(filePath);
        }

        #endregion

        #region 删除指定文件

        /// <summary> 
        /// 删除指定文件 
        /// </summary> 
        /// <param name="filePath">文件的绝对路径</param> 
        public static void DeleteFile(string filePath)
        {
            if (IsExistFile(filePath))
            {
                File.Delete(filePath);
            }
        }

        #endregion

        #region 删除指定目录 

        /// <summary>
        ///     删除指定目录
        /// </summary>
        /// <param name="targetDir">目录路径</param>
        public static void DeleteDirectory(string targetDir)
        {
            var dirInfo = new DirectoryInfo(targetDir);

            if (dirInfo.Exists)
            {
                DeleteFiles(targetDir, true);
                dirInfo.Delete(true);
            }
        }

        #endregion


        /// <summary>
        ///     创建文件路径
        ///     <para>eg:FileHelper.CreatePath(@"C:\aa\cc\dd\ee.xml");</para>
        /// </summary>
        /// <param name="path">需要创建的路径</param>
        /// <returns>是否创建成功</returns>
        public static bool CreatePath(string path)
        {
            var result = true;

            if (!string.IsNullOrEmpty(path) && !File.Exists(path))
                try
                {
                    var directory = Path.GetDirectoryName(path);
                    CreateDirectory(directory);
                    using (File.Create(path))
                    {
                    }
                }

                catch (Exception)
                {
                    result = false;
                }

            return result;
        }

        #region Fields

        /// <summary>
        ///     OF_READWRITE
        /// </summary>
        public const int OfReadwrite = 2;

        /// <summary>
        ///     OF_SHARE_DENY_NONE
        /// </summary>
        public const int OfShareDenyNone = 0x40;

        /// <summary>
        ///     路径分割符
        /// </summary>
        public const string PathSplitChar = "\\";

        /// <summary>
        ///     HFILE_ERROR
        /// </summary>
        public static readonly IntPtr HfileError = new IntPtr(-1);

        /// <summary>
        ///     从路径中获取文件名称（不包括后缀）
        ///     <para>eg:FileHelper.GetFileNameOnly(@"C:\yanzhiwei.docx");==>yanzhiwei</para>
        /// </summary>
        /// <param name="filePath">路径</param>
        /// <returns>文件名称（不包括后缀）</returns>
        public static string GetFileNameOnly(string filePath)
        {
            return Path.GetFileNameWithoutExtension(filePath);
        }

        #endregion Fields

        #region Methods

        /// <summary>
        ///     修改文件路径后缀名
        ///     <para>eg:FileHelper.CreateTempPath("jpg");</para>
        /// </summary>
        /// <param name="extension">文件后缀;eg:xml</param>
        /// <returns>临时文件路径</returns>
        public static string ChangeFileType(string extension)
        {
            var path = Path.GetTempFileName();
            return Path.ChangeExtension(path, extension);
        }

        /// <summary>
        ///     验证格式
        /// </summary>
        /// <param name="allType">所有格式;eg .jpeg|.jpg|.bmp|.gif|.png</param>
        /// <param name="chkType">被检查的格式</param>
        /// <returns>是否是符合的文件格式</returns>
        public static bool CheckValidExt(string allType, string chkType)
        {
            var flag = false;
            var data = allType.Split('|');

            foreach (var temp in data)
                if (string.Equals(temp, chkType, StringComparison.OrdinalIgnoreCase))
                {
                    flag = true;
                    break;
                }

            return flag;
        }

        /// <summary>
        ///     复制指定目录的所有文件,不包含子目录及子目录中的文件
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,表示覆盖同名文件,否则不覆盖</param>
        public static void CopyFiles(string sourceDir, string targetDir, bool overWrite)
        {
            CopyFiles(sourceDir, targetDir, overWrite, false);
        }

        /// <summary>
        ///     复制指定目录的所有文件
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
        /// <param name="copySubDir">如果为true,包含目录,否则不包含</param>
        public static void CopyFiles(string sourceDir, string targetDir, bool overWrite, bool copySubDir)
        {
            //复制当前目录文件
            foreach (var sourceFile in Directory.GetFiles(sourceDir))
            {
                var targetFile = Path.Combine(targetDir,
                    sourceFile.Substring(
                        sourceFile.LastIndexOf(PathSplitChar, StringComparison.OrdinalIgnoreCase) + 1));

                if (File.Exists(targetFile))
                {
                    if (overWrite)
                    {
                        File.SetAttributes(targetFile, FileAttributes.Normal);
                        // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                        File.Copy(sourceFile, targetFile, overWrite);
                    }
                }
                else
                {
                    File.Copy(sourceFile, targetFile, overWrite);
                }
            }

            //复制子目录
            if (copySubDir)
                foreach (var sourceSubDir in Directory.GetDirectories(sourceDir))
                {
                    var targetSubDir = Path.Combine(targetDir,
                        sourceSubDir.Substring(sourceSubDir.LastIndexOf(PathSplitChar, StringComparison.Ordinal) + 1));

                    if (!Directory.Exists(targetSubDir)) Directory.CreateDirectory(targetSubDir);

                    CopyFiles(sourceSubDir, targetSubDir, overWrite, true);
                }
        }

        /// <summary>
        ///     复制指定目录的所有文件，并把复制的文件备份到备份目录中
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
        /// <param name="copySubDir">如果为true,包含目录,否则不包含</param>
        /// <param name="backDir">备份目录</param>
        public static void CopyFiles(string sourceDir, string targetDir, bool overWrite, bool copySubDir,
            string backDir)
        {
            if (!Directory.Exists(backDir)) Directory.CreateDirectory(backDir);

            //复制当前目录文件
            foreach (var sourceFile in Directory.GetFiles(sourceDir))
            {
                var targetFile = Path.Combine(targetDir,
                    sourceFile.Substring(
                        sourceFile.LastIndexOf(PathSplitChar, StringComparison.OrdinalIgnoreCase) + 1));

                if (File.Exists(targetFile))
                {
                    if (overWrite)
                    {
                        File.SetAttributes(targetFile, FileAttributes.Normal);
                        var backFileName = Path.Combine(backDir,
                            sourceFile.Substring(sourceFile.LastIndexOf(PathSplitChar, StringComparison.Ordinal) + 1));
                        File.Copy(targetFile, backFileName, true);
                        // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                        File.Copy(sourceFile, targetFile, overWrite);
                    }
                }
                else
                {
                    File.Copy(sourceFile, targetFile, overWrite);
                }
            }

            //复制子目录
            if (copySubDir)
                foreach (var sourceSubDir in Directory.GetDirectories(sourceDir))
                {
                    var targetSubDir = Path.Combine(targetDir,
                        sourceSubDir.Substring(sourceSubDir.LastIndexOf(PathSplitChar, StringComparison.Ordinal) + 1));

                    if (!Directory.Exists(targetSubDir)) Directory.CreateDirectory(targetSubDir);

                    var backSubDir = Path.Combine(backDir,
                        targetSubDir.Substring(targetSubDir.LastIndexOf(PathSplitChar, StringComparison.Ordinal) + 1));

                    if (!Directory.Exists(backSubDir)) Directory.CreateDirectory(backSubDir);

                    CopyFiles(sourceSubDir, targetSubDir, overWrite, true, backSubDir);
                }
        }

        /// <summary>
        ///     复制本机大文件
        ///     <para>
        ///         eg:FileHelper.CopyLocalBigFile(@"C:\Users\YanZh_000\Downloads\TheInterview.mp4", @"D:\The
        ///         Interview(1080p).mp4", 1024 * 1024 * 5))
        ///     </para>
        /// </summary>
        /// <param name="fromPath">源文件的路径</param>
        /// <param name="toPath">文件保存的路径</param>
        /// <param name="eachReadLength">每次读取的长度</param>
        /// <returns>是否复制成功</returns>
        public static bool CopyLargeFile(string fromPath, string toPath, int eachReadLength)
        {
            /*
             * 知识：
             * FileStream缓冲读取和写入可以提高性能。FileStream读取文件的时候，是先讲流放入内存，经Flash()方法后将内存中（缓冲中）的数据写入件。如果文件非常大，势必消耗性能。
             *
             * 参考
             * 1：http://www.cnblogs.com/zfanlong1314/p/3922803.html
             */
            var copyResult = true;
            //将源文件 读取成文件流
            var fileStream = new FileStream(fromPath, FileMode.Open, FileAccess.Read);
            //已追加的方式 写入文件流
            var appendFile = new FileStream(toPath, FileMode.Append, FileAccess.Write);

            try
            {
                //实际读取的文件长度
                int readFileCount;

                //如果每次读取的长度小于 源文件的长度 分段读取
                if (eachReadLength < fileStream.Length)
                {
                    var buffer = new byte[eachReadLength];
                    long copyCnt = 0;

                    while (copyCnt <= fileStream.Length - eachReadLength)
                    {
                        readFileCount = fileStream.Read(buffer, 0, eachReadLength);
                        fileStream.Flush();
                        appendFile.Write(buffer, 0, eachReadLength);
                        appendFile.Flush();
                        //流的当前位置
                        appendFile.Position = fileStream.Position;
                        copyCnt += readFileCount;
                    }

                    var leftCount = (int)(fileStream.Length - copyCnt);
                    fileStream.Read(buffer, 0, leftCount);
                    fileStream.Flush();
                    appendFile.Write(buffer, 0, leftCount);
                    appendFile.Flush();
                }
                else
                {
                    //如果每次拷贝的文件长度大于源文件的长度 则将实际文件长度直接拷贝
                    var buffer = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, buffer.Length);
                    fileStream.Flush();
                    appendFile.Write(buffer, 0, buffer.Length);
                    appendFile.Flush();
                }
            }
            catch (Exception)
            {
                copyResult = false;
            }
            finally
            {
                fileStream.Close();
                appendFile.Close();
            }

            return copyResult;
        }

        /// <summary>
        ///     文件复制备份【同目录下】
        ///     <para>eg:FileHelper.CopyToBak(TestFilePath);</para>
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public static bool CopyToBak(string filePath)
        {
            bool result;

            try
            {
                var fileCount = 0;
                string bakName;

                do
                {
                    fileCount++;
                    bakName = $"{filePath}.{fileCount}.bak";
                } while (File.Exists(bakName));

                File.Copy(filePath, bakName);
                File.Delete(filePath);
                result = true;
            }
            catch (Exception)
            {
                result = false;
            }

            return result;
        }

        /// <summary>
        ///     建立子目录
        /// </summary>
        /// <param name="parentDir">目录路径</param>
        /// <param name="subDirName">子目录名称</param>
        public static void CreateDirectory(string parentDir, string subDirName)
        {
            CreateDirectory(parentDir + PathSplitChar + subDirName);
        }


        /// <summary>
        ///     根据现有路径创建临时文件路径
        /// </summary>
        /// <param name="filePath">文件全路径</param>
        /// <returns></returns>
        /// 时间：2015-12-17 14:13
        /// 备注：
        public static string CreateTempFilePath(this string filePath)
        {
            var fileInfo = new FileInfo(filePath);
            var sourceFileTemp = Path.Combine(fileInfo.DirectoryName ?? throw new InvalidOperationException(),
                Guid.NewGuid() + fileInfo.Extension);
            fileInfo.CopyTo(sourceFileTemp);
            return sourceFileTemp;
        }

    
        /// <summary>
        ///     删除指定目录的所有文件，不包含子目录
        /// </summary>
        /// <param name="targetDir">操作目录</param>
        public static void DeleteFiles(string targetDir)
        {
            DeleteFiles(targetDir, false);
        }

        /// <summary>
        ///     删除指定目录的所有文件和子目录
        /// </summary>
        /// <param name="targetDir">操作目录</param>
        /// <param name="delSubDir">如果为true,包含对子目录的操作</param>
        public static void DeleteFiles(string targetDir, bool delSubDir)
        {
            foreach (var fileName in Directory.GetFiles(targetDir))
            {
                File.SetAttributes(fileName, FileAttributes.Normal);
                File.Delete(fileName);
            }

            if (delSubDir)
            {
                var dir = new DirectoryInfo(targetDir);

                foreach (var subDi in dir.GetDirectories())
                {
                    DeleteFiles(subDi.FullName, true);
                    subDi.Delete();
                }
            }
        }

        /// <summary>
        ///     删除指定目录的所有子目录,不包括对当前目录文件的删除
        /// </summary>
        /// <param name="targetDir">目录路径</param>
        public static void DeleteSubDirectory(string targetDir)
        {
            foreach (var subDir in Directory.GetDirectories(targetDir)) DeleteDirectory(subDir);
        }

        /// <summary>
        ///     文件是否被占用
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns>是否被占用</returns>
        public static bool FileIsTake(string fileName)
        {
            if (!File.Exists(fileName)) return false; //文件不存在

            var intPtr = _lopen(fileName, OfReadwrite | OfShareDenyNone);

            if (intPtr == HfileError) return true; //文件被占用！

            CloseHandle(intPtr);
            return false;
        }


        /// <summary>
        ///     获取文件大小—kb
        ///     <para>eg:FileHelper.GetKBSize(TestFilePath);</para>
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>文件大小_kb</returns>
        public static double GetKbSize(string filePath)
        {
            double kb = 0;
            var size = GetSize(filePath);

            if (size != 0) kb = size / 1024d;

            return kb;
        }

        /// <summary>
        ///     获取文件大小—mb
        ///     <para>eg:FileHelper.GetMBSize(TestFilePath);</para>
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>文件大小_mb</returns>
        public static double GetMbSize(string filePath)
        {
            double mb = 0;
            var size = GetSize(filePath);

            if (size != 0) mb = size / 1048576d; //1024*1024==1048576;

            return mb;
        }

        /// <summary>
        ///     获取文件大小—字节
        ///     <para>eg:FileHelper.GetSize(TestFilePath);</para>
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>文件大小</returns>
        public static long GetSize(string filePath)
        {
            var buffer = ReadFile(filePath);
            return buffer == null ? 0 : buffer.Length;
        }

        /// <summary>
        ///     获取可用的文件名称
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns>返回可用的用户名称</returns>
        public static string GetValidFileName(string fileName)
        {
            return Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "").Replace(" ", string.Empty);
        }

        /// <summary>
        ///     剪切指定目录的所有文件,不包含子目录
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
        public static void MoveFiles(string sourceDir, string targetDir, bool overWrite)
        {
            MoveFiles(sourceDir, targetDir, overWrite, false);
        }

        /// <summary>
        ///     剪切指定目录的所有文件
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
        /// <param name="moveSubDir">如果为true,包含目录,否则不包含</param>
        public static void MoveFiles(string sourceDir, string targetDir, bool overWrite, bool moveSubDir)
        {
            //移动当前目录文件
            foreach (var sourceFile in Directory.GetFiles(sourceDir))
            {
                var targetFileName = Path.Combine(targetDir,
                    sourceFile.Substring(sourceFile.LastIndexOf(PathSplitChar, StringComparison.Ordinal) + 1));

                if (File.Exists(targetFileName))
                {
                    if (overWrite)
                    {
                        File.SetAttributes(targetFileName, FileAttributes.Normal);
                        File.Delete(targetFileName);
                        File.Move(sourceFile, targetFileName);
                    }
                }
                else
                {
                    File.Move(sourceFile, targetFileName);
                }
            }

            if (moveSubDir)
                foreach (var sourceSubDir in Directory.GetDirectories(sourceDir))
                {
                    var targetSubDir = Path.Combine(targetDir,
                        sourceSubDir.Substring(sourceSubDir.LastIndexOf(PathSplitChar, StringComparison.Ordinal) + 1));

                    if (!Directory.Exists(targetSubDir)) Directory.CreateDirectory(targetSubDir);

                    MoveFiles(sourceSubDir, targetSubDir, overWrite, true);
                    Directory.Delete(sourceSubDir);
                }
        }

        /// <summary>
        ///     打开文件或者文件夹
        /// </summary>
        /// <param name="path">文件夹或者文件的路径</param>
        public static void OpenFolderAndFile(string path)
        {
            Process.Start(path);
        }

        /// <summary>
        ///     将文件转换成二进制流
        ///     <para>eg:FileHelper.ReadFile(@"C:\demo.txt");</para>
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>二进制数组</returns>
        public static byte[] ReadFile(string filePath)
        {
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                var buffur = new byte[stream.Length];
                stream.Read(buffur, 0, (int)stream.Length);
                return buffur;
            }
        }

        /// <summary>
        ///     递归获取文件夹目录下文件
        /// </summary>
        /// <param name="pathName">需要递归遍历的文件夹</param>
        /// <param name="fileHanlder">遍历规则『委托』</param>
        public static void RecursiveFolder(string pathName, Action<FileInfo> fileHanlder)
        {
            var fileQueue = new Queue<string>();
            fileQueue.Enqueue(pathName);

            while (fileQueue.Count > 0)
            {
                var path = fileQueue.Dequeue();
                var pathSecurity = new DirectorySecurity(path, AccessControlSections.Access);

                if (!pathSecurity.AreAccessRulesProtected) //文件夹权限是否可访问
                {
                    var directoryInfo = new DirectoryInfo(path);

                    foreach (var diChild in directoryInfo.GetDirectories()) fileQueue.Enqueue(diChild.FullName);

                    foreach (var file in directoryInfo.GetFiles()) fileHanlder(file);
                }
            }
        }

        /// <summary>
        ///     将byte[]导出到文件
        ///     <para>eg: FileHelper.SaveFile(_bytes, _outputFilePath); </para>
        /// </summary>
        /// <param name="data">文件流</param>
        /// <param name="filePath">存储路径</param>
        public static void SaveFile(byte[] data, string filePath)
        {
            File.WriteAllBytes(filePath, data);
        }


        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);

        [DllImport("kernel32.dll")]
        private static extern IntPtr _lopen(string lpPathName, int iReadWrite);

        #endregion Methods
    }
}
